/**
 * Copyright (c) 2011 Ibrahim Abd Elkader <i.abdalkader@gmail.com> 
 * See the file COPYING for copying permission.
 */
.bss
.equ    GPIO_BASE,      0x2009C000
.equ    LPC_GPIOINT,    0x40028080
.equ    INT_VD,         0x800
.equ    INT_HD,         0x1000
.equ    INT_DK,         0x2000
.lcomm  scanline        256    /* scanline buffer */

.text
.thumb_func
.syntax unified
.align 2 
.weak   EINT3_IRQHandler
.type   EINT3_IRQHandler, %function
EINT3_IRQHandler:
    ldr     r12, =LPC_GPIOINT
    push    {r4-r7, lr}
    ldr     r7, [r12, #36]
    and     r0, r7, #INT_HD
    cbz     r0, vd_int

    /* read scanline */
    ldr     r0, =scanline
    ldr     r5, =GPIO_BASE
    add     r2, r0, #256
    loop:
    ldr     r3, [r5, #0x54]
    ands    r3, #INT_DK
    beq     loop    
    ldrb    r4, [r5, #0x36]
    strb    r4, [r0], #1
    cmp     r0, r2
    bne     loop

    /* convert to grayscale */
    ldr     r0, =scanline
    ldr     r6, =bytes
    ldr     r5, =frame_buffer
    ldr     lr, [r6]
    mov     r1, #992            
    mov     r2, #63             
    add     r5, lr

    add     lr, #128
    str     lr, [r6, #0]

    loop2:      
    /* read pixel */
    ldrh    r7, [r0], #2 

    and     r3, r1, r7, lsr  #6 
    and     r4, r2, r7, lsr  #5 
    and     r7, r7, #31         

    add     r3, r3, r4, lsl #6  
    add     r4, r3, r7, lsl #5  
    lsr     r4, #8 

    strb    r4, [r5], #1 
    tst     r5, #255            
    bne     loop2               

    /* if frame finished enable VD interrupt */
    cmp     lr, #12288
    itt eq; 
    moveq   r2, #INT_VD
    streq   r2, [r12, #48]

    /* clear HD interrupt */ 
    mov     r2, #INT_HD
    str     r2, [r12, #44]
    pop    {r4-r7, pc}
    
    vd_int:
    and     r0, r7, #INT_VD
    cbz     r0, done

    ldr     r1, =bytes
    mov     r2, #0
    str     r2, [r1]

    /* enable HD interrupt */
    mov     r0, #INT_HD
    str     r0, [r12, #48]

    /* clear  VD interrupt */ 
    mov     r0, #INT_VD
    str     r0, [r12, #44]

    done:
    pop    {r4-r7, pc}
.end
